﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AtletIS.Shared.Data;
using AtletIS.Shared.Entities;
using AtletIS.Shared.Helpers;

namespace AtletIS.Shared.Forms.Admin
{
    public partial class frmAdminDisciplineList : Form
    {
        private CompetitionEntity competition;
        private aDbDataSet.DisciplineListRow drActiveDisciplineList;
        private bool bNew, bEditMode = false;

        #region Form

        // Constructor
        public frmAdminDisciplineList(CompetitionEntity competition)
        {
            InitializeComponent();

            this.competition = competition;
            this.Icon = Properties.Resources.AtletIS64;
        }

        // Load
        private void frmAdminDisciplineList_Load(object sender, EventArgs e)
        {
            DatabaseHelper.FillCategoriesActive(this.aDbDataSet.Categories);
            DatabaseHelper.FillDisciplinesActive(this.aDbDataSet.Disciplines);

            DatabaseHelper.FillDisciplineListByCompetitionId(this.aDbDataSet.DisciplineList, this.competition.ID);
            
            this.lblTitle.Text += ": " + this.competition.Name;
            this.tsbCancel.Enabled = false;
            this.tsbSave.Enabled = false; 
        }

        #endregion

        #region DataGridView events

        // Selection changed
        private void dgvDisciplineList_SelectionChanged(object sender, EventArgs e)
        {
            if (this.dgvDisciplineList.CurrentRow == null)
                return;

            try
            {
                DataRowView drv = (DataRowView)this.dgvDisciplineList.CurrentRow.DataBoundItem;

                DateTime startTime = Convert.ToDateTime(drv["StartTime"]);

                this.nudOrder.Value = Convert.ToInt32(drv["Order"]);
                this.txtName.Text = drv["Name"].ToString();
                this.txtDescription.Text = drv["Description"].ToString();
                this.nudDay.Value = (startTime.Date - competition.DateFrom.Date).Days + 1;
                this.cbDisciplines.SelectedValue = Convert.ToInt32(drv["DisciplineId"]);
                this.cbCategories.SelectedValue = Convert.ToInt32(drv["CategoryId"]);
                this.nudMeasurementId.Value = Convert.ToInt32(drv["MeasurementId"]);
                this.chkRelay.Checked = Convert.ToBoolean(drv["Relay"]);
                this.chkVisible.Checked = Convert.ToBoolean(drv["Visible"]);

                // StartTime, RealStartTime
                this.dtpStartTime.Value = startTime;
                if (drv["RealStartTime"] != DBNull.Value)
                    this.dtpRealStartTime.Value = Convert.ToDateTime(drv["RealStartTime"]);
                else
                    this.dtpRealStartTime.Value = startTime;
            }
            catch (Exception ex)
            {
                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        // Show check points
        private void dgvDisciplineList_DoubleClick(object sender, EventArgs e)
        {
            this.OpenCheckPoints();
        }

        #endregion

        #region Toolbar events

        // New
        private void tsbNew_Click(object sender, EventArgs e)
        {
            try
            {
                bNew = true;
                bEditMode = true;
                tsbNew.Enabled = false;
                tsbEdit.Enabled = false;
                tsbDelete.Enabled = false;
                tsbCancel.Enabled = true;
                tsbSave.Enabled = true;

                tsbExport.Enabled = false;
                tsbCheckPoints.Enabled = false;

                this.nudOrder.Value += 1;
                this.txtName.Text = string.Empty;
                this.txtDescription.Text = string.Empty;
                this.nudDay.Value = 1;
                this.chkVisible.Checked = true;

                this.cbDisciplines.SelectedIndex = -1;
                this.cbCategories.SelectedIndex = -1;

                this.drActiveDisciplineList = aDbDataSet.DisciplineList.NewDisciplineListRow();

                this.drActiveDisciplineList["CompetitionId"] = competition.ID;
                this.drActiveDisciplineList["ParentId"] = 0;
                this.drActiveDisciplineList["Status"] = 1;
                this.drActiveDisciplineList["Params"] = string.Empty;
                this.drActiveDisciplineList["SecondaryOrder"] = 0;

                this.drActiveDisciplineList["Wind"] = DBNull.Value;
                this.drActiveDisciplineList["ShowSplits"] = true; 

                this.drActiveDisciplineList["Active"] = true; 
                this.drActiveDisciplineList["Sync"] = false;
                this.drActiveDisciplineList["WebId"] = 0;
                this.drActiveDisciplineList["Visible"] = true;

                this.gbList.Enabled = false;
                this.gbDetails.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, "Zoznam disciplín - pridať", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // Edit
        private void tsbEdit_Click(object sender, EventArgs e)
        {
            try
            {
                bNew = false;
                bEditMode = true;
                tsbNew.Enabled = false;
                tsbEdit.Enabled = false;
                tsbDelete.Enabled = false;
                tsbCancel.Enabled = true;
                tsbSave.Enabled = true;

                tsbExport.Enabled = false;
                tsbCheckPoints.Enabled = false;

                DataRowView drv = (DataRowView)dgvDisciplineList.CurrentRow.DataBoundItem;
                this.drActiveDisciplineList = (aDbDataSet.DisciplineListRow)drv.Row;

                gbList.Enabled = false;
                gbDetails.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, "Zoznam disciplín - editovať", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // Delete
        private void tsbDelete_Click(object sender, EventArgs e)
        {
            if (dgvDisciplineList.CurrentRow == null)
                return;

            if (MessageBox.Show("Naozaj chcete zmazať vybratý záznam?", "Zoznam disciplín", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                return;

            try
            {
                DataRow dr = ((DataRow)((DataRowView)dgvDisciplineList.CurrentRow.DataBoundItem).Row);
                //dr.Delete();
                dr["Active"] = 0;
                dr["Modified"] = DateTime.Now;
                taDisciplineList.Update(dr);
            }
            catch
            {
                MessageBox.Show("Záznam nemôže byť zmazaný!", "Zoznam disciplín - zmazať", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                DatabaseHelper.FillDisciplineListByCompetitionId(this.aDbDataSet.DisciplineList, this.competition.ID);
            }
        }

        // Cancel
        private void tsbCancel_Click(object sender, EventArgs e)
        {
            tsbNew.Enabled = true;
            tsbEdit.Enabled = true;
            tsbDelete.Enabled = true;
            tsbCancel.Enabled = false;
            tsbSave.Enabled = false;

            tsbExport.Enabled = true;
            tsbCheckPoints.Enabled = true;

            gbList.Enabled = true;
            gbDetails.Enabled = false;

            dgvDisciplineList_SelectionChanged(null, null);
        }

        // Save
        private void tsbSave_Click(object sender, EventArgs e)
        {
            bEditMode = false;

            try
            {
                if (cbDisciplines.SelectedIndex == -1)
                {
                    MessageBox.Show("Vyberte disciplínu!", "Zoznam disciplín - uloženie", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (cbCategories.SelectedIndex == -1)
                {
                    MessageBox.Show("Vyberte kategóriu!", "Zoznam kategóriu - uloženie", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                
                this.drActiveDisciplineList["Order"] = this.nudOrder.Value;
                this.drActiveDisciplineList["Name"] = this.txtName.Text;
                this.drActiveDisciplineList["Description"] = this.txtDescription.Text;
                this.drActiveDisciplineList["DisciplineId"] = this.cbDisciplines.SelectedValue;
                this.drActiveDisciplineList["CategoryId"] = this.cbCategories.SelectedValue;
                this.drActiveDisciplineList["DisciplineCode"] = ((DataRowView)this.cbDisciplines.SelectedItem)["Code"];
                this.drActiveDisciplineList["MeasurementId"] = this.nudMeasurementId.Value;
                this.drActiveDisciplineList["Relay"] = this.chkRelay.Checked;
                this.drActiveDisciplineList["Visible"] = this.chkVisible.Checked;
                this.drActiveDisciplineList["Modified"] = DateTime.Now;

                // StartTime, RealStartTime
                var startDate = this.competition.DateFrom.AddDays(Convert.ToInt32(nudDay.Value - 1));
                
                this.drActiveDisciplineList["StartTime"] = new DateTime(startDate.Year, startDate.Month, startDate.Day, 
                    this.dtpStartTime.Value.Hour, this.dtpStartTime.Value.Minute, 0);
                
                if (this.chkRealStartTime.Checked)
                {
                    this.drActiveDisciplineList["RealStartTime"] = new DateTime(startDate.Year, startDate.Month, startDate.Day,
                        this.dtpRealStartTime.Value.Hour, this.dtpRealStartTime.Value.Minute, this.dtpRealStartTime.Value.Second);
                }

                if (bNew)
                {
                    this.drActiveDisciplineList["AutoOrder"] = DatabaseHelper.GetDisciplineListNewAutoOrder(competition.ID);
                    
                    aDbDataSet.DisciplineList.Rows.Add(this.drActiveDisciplineList);
                    this.taDisciplineList.Update(aDbDataSet.DisciplineList);
                }
                else
                {
                    this.taDisciplineList.Update(this.drActiveDisciplineList);
                }

                DatabaseHelper.FillDisciplineListByCompetitionId(this.aDbDataSet.DisciplineList, this.competition.ID);

                tsbNew.Enabled = true;
                tsbEdit.Enabled = true;
                tsbDelete.Enabled = true;
                tsbCancel.Enabled = false;
                tsbSave.Enabled = false;

                tsbExport.Enabled = true;
                tsbCheckPoints.Enabled = true;

                gbDetails.Enabled = false;
                gbList.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace, "Zoznam disciplín - uloženie", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // Export
        private void tsbExport_Click(object sender, EventArgs e)
        {
            DisciplineListHelper.Export(competition);
        }

        // Show check points
        private void tsbCheckPoints_Click(object sender, EventArgs e)
        {
            this.OpenCheckPoints();
        }

        // Close
        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region Disciplines, categories combo events

        // Discipline changed
        private void cbDisciplines_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bEditMode)
            {
                txtName.Text = string.Empty;
                if (cbDisciplines.SelectedItem != null)
                {
                    if (chkAlterNames.Checked & !string.IsNullOrEmpty(((DataRowView)cbDisciplines.SelectedItem)["AlterName"].ToString()))
                    {
                        txtName.Text += ((DataRowView)cbDisciplines.SelectedItem)["AlterName"].ToString();
                    }
                    else
                    {
                        txtName.Text += ((DataRowView)cbDisciplines.SelectedItem)["Name"].ToString();
                    }
                }
                if (cbCategories.SelectedItem != null)
                {
                    if (txtName.Text != string.Empty)
                    {
                        txtName.Text += " - ";
                    }

                    if (chkAlterNames.Checked & !string.IsNullOrEmpty(((DataRowView)cbCategories.SelectedItem)["AlterName"].ToString()))
                    {
                        txtName.Text += ((DataRowView)cbCategories.SelectedItem)["AlterName"].ToString();
                    }
                    else
                    {
                        txtName.Text += ((DataRowView)cbCategories.SelectedItem)["Name"].ToString();
                    }
                }
            }
        }

        // Category changed
        private void cbCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (bEditMode)
            {
                txtName.Text = string.Empty;
                if (cbDisciplines.SelectedItem != null)
                {
                    if (chkAlterNames.Checked & !string.IsNullOrEmpty(((DataRowView)cbDisciplines.SelectedItem)["AlterName"].ToString()))
                    {
                        txtName.Text += ((DataRowView)cbDisciplines.SelectedItem)["AlterName"].ToString();
                    }
                    else
                    {
                        txtName.Text += ((DataRowView)cbDisciplines.SelectedItem)["Name"].ToString();
                    }
                }
                if (cbCategories.SelectedItem != null)
                {
                    if (txtName.Text != string.Empty)
                    {
                        txtName.Text += " - ";
                    }

                    if (chkAlterNames.Checked & !string.IsNullOrEmpty(((DataRowView)cbCategories.SelectedItem)["AlterName"].ToString()))
                    {
                        txtName.Text += ((DataRowView)cbCategories.SelectedItem)["AlterName"].ToString();
                    }
                    else
                    {
                        txtName.Text += ((DataRowView)cbCategories.SelectedItem)["Name"].ToString();
                    }
                }
            }
        }

        #endregion

        #region Edit control events

        // Edit real start time
        private void chkRealStartTime_CheckedChanged(object sender, EventArgs e)
        {
            this.dtpRealStartTime.Enabled = this.chkRealStartTime.Checked;
        }

        #endregion

        #region Check-points

        // Show check-points
        private void OpenCheckPoints()
        {
            try
            {
                if (dgvDisciplineList.CurrentRow == null)
                    return;

                int selectedDisciplineListId = Convert.ToInt32(((DataRowView)dgvDisciplineList.CurrentRow.DataBoundItem)["ID"]);

                if (selectedDisciplineListId != 0)
                {
                    frmAdminCheckPoints myCheckPointForm = new frmAdminCheckPoints(selectedDisciplineListId);
                    myCheckPointForm.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        #endregion

    }
}
